/**
 * Created with JetBrains WebStorm.
 * User: thaidoanhong
 * Date: 4/17/13
 * Time: 10:12 PM
 * To change this template use File | Settings | File Templates.
 */
var PropertyEditor = Class.create({

    initialize: function(editorId){
        this.editorId = editorId;
        this.targetElement = null;

        this.divTag = $(editorId);

        $j(this.divTag).html("<div class='table-top'>"
                            +       "<b>" + "</b>"
                            + "</div>"
                            + "<div class='datagrid'></div>");
        },
    load: function(targetElement){
        this.targetElement = targetElement;
        //Set title
        $j("#"+this.editorId).find("b").html(targetElement.id);

        var attributeList = this.targetElement.attributeList;

        var table = document.createElement("table");
        var tbody = document.createElement("tbody");

        for(var k=0; k< attributeList.getSize();k++){
            var key = attributeList.attributes[k].key;
            var type = attributeList.attributes[k].type;
            var name = attributeList.attributes[k].name;

            var tr = document.createElement("tr");
            $j(tr).html(
                "<td class='property-name'>" + name + "</td>" +
                "<td class='property-value'></td>");
            $j(tr).attr("key", key);
            if (key == "color")
            {
                // color input
                var input = $j("<input type='color' />")
                $j(input).val(MyTools.rgb2hex(this.targetElement.getValueFromKey(key)));
                //input.type = "color";
                //input.value = ;
                $j(input).css("visible", "hidden");
                $j(tr).find(".property-value").append($j(input));
                $j(tbody).append($j(tr));

                $j(input).spectrum(null);



                // on value change handler
                $j(input).change(propertyValueChange);
            }
            else if(key=="visibility"){
                // create radio input
                var labelVisible = document.createElement("label");
                labelVisible.innerHTML = "Visible";
                var inputVisible = document.createElement("input");
                inputVisible.type="radio";
                inputVisible.value = "visible"
                inputVisible.name = "visibility";
                var labelHidden = document.createElement("label");
                labelHidden.innerHTML = "Hidden";
                var inputHidden = document.createElement("input");
                inputHidden.type="radio";
                inputHidden.value = "hidden"
                inputHidden.innerHTML = "Hidden";
                inputHidden.name = "visibility";

                if(this.targetElement.getValueFromKey(key) == "visible")
                    inputVisible.checked = true;
                else
                    inputHidden.checked =true;

//                var input = document.createElement("div") ;
//                var html= "<input type='radio'  name='sex' id='radio1'  onchange='propertyValueChange(e)' value='visible'  > Visible</input>";
//                html += "<input type='radio' name='sex' id='radio2'  onchange='propertyValueChange(e)' value='hidden' > Hidden</input>";
//                input.innerHTML = html;

                $j(tr).find(".property-value").append($j(inputVisible));
                $j(tr).find(".property-value").append($j(labelVisible));
                $j(tr).find(".property-value").append($j(inputHidden));
                $j(tr).find(".property-value").append($j(labelHidden));
                // $j(tr).find(".property-value").append($j(tr).attr("dataType"));
                $j(tbody).append($j(tr));

                // on value change handler
                $j(inputVisible).change(propertyValueChange);
                $j(inputHidden).change(propertyValueChange);

            }
            else if((type == "image" && key == "image")
                    ||(type == "video" && key == "poster")
                    ||(type == "audio" && key == "icon")){
                var input = document.createElement("input");
                input.type = "text";
                input.value = this.targetElement.getValueFromKey(key)  ;
                input.size = 20;

                //$j(input).prop("readonly", true);

                $j(tr).find(".property-value").append($j(input));

                $j(tbody).append($j(tr));
                $j(input).change(propertyValueChange);

                // on value change handler
                $j(input).on("click", function(){
                    var _input = this;

                    $j("#" + Static.dialogImageChooser).dialog({
                        autoOpen: true,
                        width: 500,
                        modal: true,
                        position: [300,100]
                    });

                    $j.getJSON("getImagesList.php", function(data){

                        $j("#"+Static.dialogImageChooser).empty();
                        $j.each(data, function(index, value){
                            var finalDelimiter = value.lastIndexOf("/");
                            var firstStr = value.substring(0, finalDelimiter+1);
                            var fileName = value.substring(finalDelimiter+1)
                            var thumbPath = firstStr + "thumbnail/" + fileName;

                            $j("<img/>").attr("src", thumbPath).attr("filePath", value).attr("title", fileName).attr("alt", fileName)
                                .appendTo("#"+Static.dialogImageChooser).addClass("image-chooser").on("click", function(){
                                    $j(_input).val(value);
                                    $j("#" + Static.dialogImageChooser).dialog("close");
                                    $j(_input).trigger("change");
                                });
                        });
                    });
                });
            }
            else if(type == "video" && key == "src"){
                var input = document.createElement("input");
                input.type = "text";
                input.value = this.targetElement.getValueFromKey(key)  ;

                $j(tr).find(".property-value").append($j(input));

                $j(tbody).append($j(tr));
                $j(input).change(propertyValueChange);

                $j(input).on("click", function(){
                    var _input = this;

                    $j("#" + Static.dialogImageChooser).dialog({
                        autoOpen: true,
                        width: 500,
                        modal: true,
                        position: [300,100]
                    });

                    $j.getJSON("getVideoList.php", function(data){
                        $j("#"+Static.dialogImageChooser).empty();

                        var ulTag = $j("<ul></ul>").addClass("video").appendTo("#"+Static.dialogImageChooser);

                        $j.each(data, function(index, value){
                            var finalDelimiter = value.lastIndexOf("/");
                            var firstStr = value.substring(0, finalDelimiter+1);
                            var fileName = value.substring(finalDelimiter+1)

                            var aTag = $j("<a></a>").html("<strong>" + fileName +"</strong>").attr("filePath", value);
                            $j("<li></li>").append(aTag).appendTo(ulTag);

                            $j(aTag).on("click", function(){
                                $j(_input).val(value);
                                $j("#" + Static.dialogImageChooser).dialog("close");
                                $j(_input).trigger("change");
                            });

                        });
                    });
                });
            }
            else if(type == "audio" && key == "src"){
                var input = document.createElement("input");
                input.type = "text";
                input.value = this.targetElement.getValueFromKey(key)  ;

                $j(tr).find(".property-value").append($j(input));

                $j(tbody).append($j(tr));
                $j(input).change(propertyValueChange);

                $j(input).on("click", function(){
                    var _input = this;

                    $j("#" + Static.dialogImageChooser).dialog({
                        autoOpen: true,
                        width: 500,
                        modal: true,
                        position: [300,100]
                    });

                    $j.getJSON("getAudioList.php", function(data){
                        $j("#"+Static.dialogImageChooser).empty();

                        var ulTag = $j("<ul></ul>").addClass("video").appendTo("#"+Static.dialogImageChooser);

                        $j.each(data, function(index, value){
                            var finalDelimiter = value.lastIndexOf("/");
                            var firstStr = value.substring(0, finalDelimiter+1);
                            var fileName = value.substring(finalDelimiter+1)

                            var aTag = $j("<a></a>").html("<strong>" + fileName +"</strong>").attr("filePath", value);
                            $j("<li></li>").append(aTag).appendTo(ulTag);

                            $j(aTag).on("click", function(){
                                $j(_input).val(value);
                                $j("#" + Static.dialogImageChooser).dialog("close");
                                $j(_input).trigger("change");
                            });

                        });
                    });
                });
            }
            else if(key=="fontFamily"){
                var html = "";
                for (var i = 0; i < Static.fonts.length; i++)
                    html += "<option value=" +
                        Static.fonts[i] + ">" +
                        Static.fonts[i] + "</option>";

                var input = document.createElement("select");
                input.innerHTML = html;
                //console.log(this.targetElement.getValueFromKey(key).toString());
                //console.log("index : "+ Static.fonts.indexOf(this.targetElement.getValueFromKey(key)));
                input.selectedIndex = Static.fonts.indexOf(this.targetElement.getValueFromKey(key));
                $j(tr).find(".property-value").append($j(input));

                $j(tbody).append($j(tr));

                // on value change handler
                $j(input).change(propertyValueChange);
            }
            else if(key == "font-style"){
                var html = "";
                for (var i = 0; i < Static.fontStyle.length; i++)
                    html += "<option value=" +
                        Static.fontStyle[i] + ">" +
                        Static.fontStyle[i] + "</option>";

                var input = document.createElement("select");
                input.innerHTML = html;
                //console.log(this.targetElement.getValueFromKey(key).toString());
                //console.log("index : "+ Static.fonts.indexOf(this.targetElement.getValueFromKey(key)));
                input.selectedIndex = Static.fontStyle.indexOf(this.targetElement.getValueFromKey(key));
                $j(tr).find(".property-value").append($j(input));

                $j(tbody).append($j(tr));

                // on value change handler
                $j(input).change(propertyValueChange);
            }
            else if(key == "text-align"){
                var html = "";
                for (var i = 0; i < Static.textAlign.length; i++)
                    html += "<option value=" +
                        Static.textAlign[i] + ">" +
                        Static.textAlign[i] + "</option>";

                var input = document.createElement("select");
                input.innerHTML = html;
                //console.log(this.targetElement.getValueFromKey(key).toString());
                //console.log("index : "+ Static.fonts.indexOf(this.targetElement.getValueFromKey(key)));
                input.selectedIndex = Static.textAlign.indexOf(this.targetElement.getValueFromKey(key));
                $j(tr).find(".property-value").append($j(input));

                $j(tbody).append($j(tr));

                // on value change handler
                $j(input).change(propertyValueChange);
            }
            else if(key == "content"){//Text cua MyText
                var input = document.createElement("textarea");
                input.type = "text";
                input.value = this.targetElement.getValueFromKey(key);
                input.rows = 4;
                $j(tr).find(".property-value").append($j(input));

                $j(tbody).append($j(tr));

                // on value change handler
                $j(input).change(propertyValueChange);
            }
            else if(key == "onActivate"){

                var actionSelection = new Element("select", {name: "action"});
                $j("<option></option>").attr("value", "animate").html("Animate").appendTo(actionSelection);
                $j("<option></option>").attr("value", "navigate").html("Navigate").appendTo(actionSelection);

                var animateSelection = new Element("select", {name: "params"});
                $j(animateSelection).css("display", "none").attr("actionType", "animate");
                $j("<option></option>").attr("value", "").html("").appendTo(animateSelection);
                for(var i = 0; i < Static.animations.length; i++){
                    $j("<option></option>").attr("value", Static.animations[i]).html(Static.animations[i]).appendTo(animateSelection);
                }

                var navigationSelection = new Element("select", {name: "params"});
                $j(navigationSelection).css("display", "none").attr("actionType", "navigate");
                $j("<option></option>").attr("value", "").html("").appendTo(navigationSelection);

                var pageIdArray = new Array();
                for(var i = 0; i < Global.currentBook.pages.length; i++){
                    pageIdArray[i] = Global.currentBook.pages[i].id;
                    $j("<option></option>").attr("value", Global.currentBook.pages[i].id).html(Global.currentBook.pages[i].id).appendTo(navigationSelection);
                }

                var value = this.targetElement.getValueFromKey(key);
                if(value.action == "navigate"){
                    $j(actionSelection).find("option[value='navigate']").prop("selected", true);
                    $j(navigationSelection).css("display", "block");
                }
                else if(value.action == "animate"){
                    $j(actionSelection).find("option[value='animate']").prop("selected", true);
                    $j(animateSelection).css("display", "block");
                }

                navigationSelection.selectedIndex = pageIdArray.indexOf(value.navigate) + 1;
                animateSelection.selectedIndex = Static.animations.indexOf(value.animate) + 1;


                $j(tr).find(".property-value").append("<strong>Action</strong>").append(actionSelection).append('<br/><strong>Params</strong>')
                    .append(animateSelection).append(navigationSelection);
                $j(tbody).append($j(tr));

                $j(actionSelection).change(propertyValueChange);
                $j(navigationSelection).change(propertyValueChange);
                $j(animateSelection).change(propertyValueChange);
            }
            else if(["left", "top", "width", "height", "font-size"].indexOf(key) != -1){
                var input = document.createElement("input");
                input.type = "text";
                input.value = this.targetElement.getValueFromKey(key).replace(/([\d.]+)(px|pt|em|%)/,'$1');
                //input.size = 20;
                $j(tr).find(".property-value").append($j(input));

                $j(tbody).append($j(tr));

                // on value change handler
                $j(input).change(propertyValueChange);
                //Xu ly viec nhan nut enter
                $j(input).keyup(function(e){
                    if(e.keyCode == 13){
                        $j(this).trigger("change");
                    }
                });
            }
            else{
                // input html
                var input = document.createElement("input");
                input.type = "text";
                input.value = this.targetElement.getValueFromKey(key);
                //input.size = 20;
                $j(tr).find(".property-value").append($j(input));

                $j(tbody).append($j(tr));

                $j(input).change(propertyValueChange);
                // on value change handler
                $j(input).keyup(function(e){
                    if(e.keyCode == 13){
                        $j(this).trigger("change");
                    }
                });
            }


        }
        // add the header and body to table
        $j(table).append($j(tbody));

        // update innerHTML of parent div
        $j("#" + this.editorId + " .datagrid").empty().append($j(table));

        var _this = this;
        function propertyValueChange(e)
        {
            var _key = $j(this).parents("tr:first").attr("key");

            if(_key == "onActivate"){
                var parent = $j(this).parent();
                //Phai xu ly cai field nay rieng vi no co value dang. phuc'
                var _action = parent.find("select[name='action'] option:selected").val();
                $j(parent).find("select[name='params']").css("display", "none");
                if(_action == "animate"){
                    $j(parent).find("select[actionType='animate']").css("display", "block");
                }
                else if(_action == "navigate"){
                    $j(parent).find("select[actionType='navigate']").css("display", "block");
                }

                var val = new Object();
                val.navigate = $j(parent).find("select[actionType='navigate'] option:checked").val() || "";
                val.animate = $j(parent).find("select[actionType='animate'] option:checked").val() || "";
                val.action = _action;

                _this.onChange({key: _key, value: val});
            }
            else{
                var _val = $j(this).val();

                if (_key == "visibility"){
                    _val = $j('input:radio[name=visibility]:checked').val();
                    _this.onChange({ key: _key, value: _val });
                }
                else if(["left", "top", "width", "height", "font-size"].indexOf(_key) != -1){
                    _val += "px";
                    _this.onChange({ key: _key, value: _val });

                    var afterVal = _this.targetElement.getValueFromKey(_key);
                    if(afterVal != _val){
                        alert("Invalid value !");
                        $j(this).val(afterVal.replace(/([\d.]+)(px|pt|em|%)/,'$1'));
                    }
                    else{
                        $j(this).blur();
                    }
                }
                else if(["color", "image", "fontFamily", "content", "font-style", "textAlign"].indexOf(_key) != -1){
                    _this.onChange({ key: _key, value: _val });
                    $j("#fake-input").focus();
                }
                else if(_key == "id"){
                    //Kiem tra xem id moi da co chua
                    if($j("#"+_val).length > 0){
                        //neu id da ton tai thi alert
                        alert("The id has been already taken! Please choose another one");
                        $j(this).focus();
                    }
                    else{
                        //Thay doi lai id cua bien global, dung de xac dinh element nao dang dc select
                        Global.currentSelectedEle = _val;
                        //
                        _this.onChange({ key: _key, value: _val });
                        //Reload lai elementsView
                        Global.elementsView.reload();
                        //Load lai propertyEditor voi id moi
                        Global.propertyEditor.load(_this.targetElement);
                    }

                }
                else {
                    _this.onChange({ key: _key, value: _val });
                    var afterVal = _this.targetElement.getValueFromKey(_key);
                    if(afterVal != _val){
                        alert("Invalid value !");
                        $j(this).val(afterVal);
                        $j(this).focus();
                    }
                    else{
                        $j(this).blur();
                    }
                }
            }


        };
    },
    onChange: function(params){
        MyTools.viewThumbnail(this.targetElement.parent.id);
        Global.undoRedo.pushUndoStack("ELEMENT_PROPERTY", this.targetElement.toJSON());
        this.targetElement.setValueByKey(params.key,params.value);
    },
    clear: function(){
        this.targetElement = null;
        //Xoa title
        $j("#"+this.editorId).find("b").empty();
        //Xoa datagrid
        $j("#" + this.editorId + " .datagrid").empty();
    }
})
